import 'dart:async';
import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:sui_shou_pai/Utils/aes_util.dart';
import 'package:sui_shou_pai/Utils/storage_util.dart';
import 'package:sui_shou_pai/my/init_info/init_information.dart';
import 'package:sui_shou_pai/network/http_config.dart';
import 'package:sui_shou_pai/network/http_request.dart';

class UpdatePhone extends StatefulWidget {
  @override
  _UpdatePhoneState createState() => _UpdatePhoneState();
}

class _UpdatePhoneState extends State<UpdatePhone> {
  bool isButtonEnable = true; //按钮状态  是否可点击
  String buttonText = '发送验证码'; //初始文本
  String phone =
      "${InitInformation.phone.substring(0, 3)}****${InitInformation.phone.substring(7, 11)}";
  int count = 60; //初始倒计时时间
  Timer timer; //倒计时的计时器
  TextEditingController newPhoneController = TextEditingController();
  TextEditingController verifyCodeController = TextEditingController();

  void _buttonClickListen() {
    setState(() {
      if (isButtonEnable) {
        //当按钮可点击时
        isButtonEnable = false; //按钮状态标记
        _initTimer();

        return null; //返回null按钮禁止点击
      } else {
        //当按钮不可点击时
//        debugPrint('false');
        return null; //返回null按钮禁止点击
      }
    });
  }

  void _initTimer() {
    timer = new Timer.periodic(Duration(seconds: 1), (Timer timer) {
      count--;
      setState(() {
        if (count == 0) {
          timer.cancel(); //倒计时结束取消定时器
          isButtonEnable = true; //按钮可点击
          count = 60; //重置时间
          buttonText = '发送验证码'; //重置按钮文本
        } else {
          buttonText = '重新发送($count)'; //更新文本内容
        }
      });
    });
  }

  @override
  void dispose() {
    timer?.cancel(); //销毁计时器
    timer = null;
    newPhoneController?.dispose();
    verifyCodeController?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("修改手机号"),
      ),
      body: Material(
        child: SingleChildScrollView(
          child: Container(
            child: Column(
//        mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Container(
                  color: Colors.white,
                  padding: EdgeInsets.only(left: 10, right: 10),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
//                  crossAxisAlignment: CrossAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.baseline,
                    textBaseline: TextBaseline.ideographic,
                    children: <Widget>[
                      Container(
                        width: 60,
                        child: Text(
                          '新手机号',
                          style:
                              TextStyle(fontSize: 15, color: Color(0xff333333)),
                        ),
                      ),
                      Expanded(
                        child: Padding(
                          padding:
                              EdgeInsets.only(left: 20, right: 15, top: 15),
                          child: TextFormField(
                            keyboardType: TextInputType.number,
                            maxLines: 1,
                            onSaved: (value) {},
                            controller: newPhoneController,
                            textAlign: TextAlign.left,
                            inputFormatters: [
                              LengthLimitingTextInputFormatter(11)
                            ],
                            decoration: InputDecoration(
                              hintText: ("请输入新手机号"),
                              contentPadding:
                                  EdgeInsets.only(top: -5, bottom: 0),
                              hintStyle: TextStyle(
                                color: Color(0xff999999),
                                fontSize: 15,
                              ),
                              alignLabelWithHint: true,
                              border: OutlineInputBorder(
                                  borderSide: BorderSide.none),
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                Container(
                  color: Colors.white,
                  padding: EdgeInsets.only(left: 10, right: 10),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
//                  crossAxisAlignment: CrossAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.baseline,
                    textBaseline: TextBaseline.ideographic,
                    children: <Widget>[
                      Container(
                        width: 60,
                        child: Text(
                          '验证码',
                          style:
                              TextStyle(fontSize: 15, color: Color(0xff333333)),
                        ),
                      ),
                      Expanded(
                        child: Padding(
                          padding:
                              EdgeInsets.only(left: 20, right: 15, top: 15),
                          child: TextFormField(
                            keyboardType: TextInputType.number,
                            maxLines: 1,
                            onSaved: (value) {},
                            controller: verifyCodeController,
                            textAlign: TextAlign.left,
                            inputFormatters: [
                              LengthLimitingTextInputFormatter(6)
                            ],
                            decoration: InputDecoration(
                              hintText: ('填写验证码'),
                              contentPadding:
                                  EdgeInsets.only(top: -5, bottom: 0),
                              hintStyle: TextStyle(
                                color: Color(0xff999999),
                                fontSize: 15,
                              ),
                              alignLabelWithHint: true,
                              border: OutlineInputBorder(
                                  borderSide: BorderSide.none),
                            ),
                          ),
                        ),
                      ),
                      Container(
                        width: 120,
                        child: FlatButton(
                          disabledColor: Colors.grey.withOpacity(0.1),
                          //按钮禁用时的颜色
                          disabledTextColor: Colors.white,
                          //按钮禁用时的文本颜色
                          textColor: isButtonEnable
                              ? Colors.white
                              : Colors.black.withOpacity(0.2),
                          //文本颜色
                          color: isButtonEnable
                              ? Color(0xff44c5fe)
                              : Colors.grey.withOpacity(0.1),
                          //按钮的颜色
                          splashColor: isButtonEnable
                              ? Colors.white.withOpacity(0.1)
                              : Colors.transparent,
                          onPressed: () {
                            setState(() {
                              _buttonClickListen();
                            });
                          },
//                        child: Text('重新发送 (${secondSy})'),
                          child: Text(
                            '$buttonText',
                            style: TextStyle(
                              fontSize: 13,
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                Container(
                  width: double.infinity,
                  height: 45,
                  margin: EdgeInsets.only(top: 50, left: 10, right: 10),
                  child: ElevatedButton(
                    onPressed: () {
                      updatePhone();
                    },
                    child: Text(
                      '确定',
                      style: TextStyle(color: Colors.white, fontSize: 15),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  bool updatePhone() {
    String phone = newPhoneController.text;
    String verifyCode = verifyCodeController.text;
    if (checkPhone(phone) && checkVerifyCode(verifyCode)) {
      updatePhoneAction(phone);
      return true;
    } else {
      return false;
    }
  }

  bool checkPhone(String phone) {
    if (phone == null) {
      Fluttertoast.showToast(msg: "请输入手机号");
      return false;
    } else if (phone.length != 11) {
      Fluttertoast.showToast(msg: "手机号格式错误");
      return false;
    } else {
      return true;
    }
  }

  bool checkVerifyCode(verifyCode) {
    if (verifyCode == null) {
      Fluttertoast.showToast(msg: "请输入验证码");
      return false;
    } else if (verifyCode != "1234") {
      Fluttertoast.showToast(msg: "验证码错误");
      return false;
    }
    if (verifyCode == "1234") {
      return true;
    }
    Fluttertoast.showToast(msg: "验证码错误");
    return false;
  }

  Future<bool> updatePhoneAction(phone) async {
    HttpRequest.request("$BASE_URL/employee/updatePhone",
            method: "post",
            data: {
              "employeeId": InitInformation.employeeId,
              "phone": AesUtil.aesEncrypt(phone)
            },
            token: await StorageUtil.getStringItem("token"))
        .then((value) {
      var data = json.decode(value.toString());
      if (data["code"] == 200) {
        Fluttertoast.showToast(msg: "手机号修改成功");
        Navigator.pop(context);
        return true;
      } else {
        Fluttertoast.showToast(msg: "手机号修改失败");
        return false;
      }
    });
  }
}
